<?php
/**
 * Introduction: 生成客户端需要的 wx.config
 * @author: 杨陈鹏
 * @email: yangchenpeng@cdlinglu.com
 */

namespace Think\Wxpay\DriverApp;


class JsSdk
{
    /**
     * Introduction: 获取jsApi
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function getJsSdk(){


        //return $this->_getAccessToken();

        $jsapi_ticket =  $this->_getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        //$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

        $data = I('param.data');

        $url = urldecode($data['url']);//$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        $timestamp = NOW_TIME;

        $nonceStr = $this->_createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "jsapi_ticket" => $jsapi_ticket,
            "appId"         => C('WeChat_APP.APPID'),
            "nonceStr"      => $nonceStr,
            "timestamp"     => $timestamp,
            "url"           => $url,
            "signature"     => $signature,
            "rawString"     => $string
        );

        return $signPackage;


    }


    /**
     * Introduction: 生成随机字符串
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    private function _createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * Introduction: 获取AccessToken
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function _getAccessToken()
    {

        $ip = get_client_ip();

        $path = CACHE_PATH.'WeChat/js_sdk/';

        $cache_file = $path.$ip.'_access_token.json';

        if(is_file($cache_file)){

            $data = json_decode(file_get_contents($cache_file),true);

            if ($data && ($data['expires_in'] > NOW_TIME)) {

                return $data['access_token'];

            } else {

                @unlink($cache_file);

            }

        }

        $config = C('WeChat_APP');

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$config['APPID']}&secret={$config['APPSECRET']}";

        $result = json_decode($this->httpGet($url),true);

        //如果获取成功进行缓存

        if(!is_dir($path))
            mkdir($path,0777,true);

        $result['expires_in'] = ($result['expires_in'] + NOW_TIME) - 200;

        file_put_contents($cache_file,json_encode($result));


        return $result['access_token'];

    }

    /**
     * Introduction: 获取js_api_ticket
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    private function _getJsApiTicket()
    {



        //读取缓存
        $ip = get_client_ip();

        $path = CACHE_PATH.'WeChat/js_sdk/';

        $cache_file = $path.$ip.'_ticket.json';

        if(is_file($cache_file)) {

            $data = json_decode(file_get_contents($cache_file), true);

            if ($data && ($data['expires_in'] > NOW_TIME)){

                return $data['ticket'];

            } else {

                @unlink($cache_file);

            }

        }

        $access_token =  $this->_getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$access_token";

        $res = json_decode($this->httpGet($url),true);

        $res['expires_in'] = $res['expires_in'] + NOW_TIME - 200;

        file_put_contents($cache_file,json_encode($res));

        return $res['ticket'];



    }
    /**
     * Introduction: curl Get请求
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    private function httpGet($url) {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;

    }
}